package com.trade.system.security;

import com.trade.module.base.entity.LoginLog;
import com.trade.module.base.entity.User;
import com.trade.module.base.service.LoginLogService;
import com.trade.common.utils.ApplicationContextUtil;
import com.trade.common.utils.Constants;
import com.trade.common.utils.IdGenerator;
import com.trade.common.utils.NetUtil;
import lombok.extern.log4j.Log4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * Class Description: 登录成功跳转
 *
 * @Version v1.0 2017/4/22 3:40
 * @JDK version 1.8.0_51
 * @Author zfb
 */
@Log4j
public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    /**
     * 身份认证
     *
     * @param request 请求
     * @param response 响应
     * @param authentication 身份验证
     * @throws ServletException servlet异常
     * @throws IOException  Io异常
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws ServletException,
            IOException {
        //获得授权后可得到用户信息，使用userService进行登录用户存储
        User userDetails =(User)authentication.getPrincipal();
        //输出登陆提示信息
        log.info("管理员 "+userDetails.getAccount()+" 登录，IP:"+ NetUtil.getIp(request));
        loginSave(userDetails,request);
        //.....
        super.onAuthenticationSuccess(request,response,authentication);
    }

    private void loginSave(User user, HttpServletRequest request){
        LoginLogService service = ApplicationContextUtil.getBean("loginLogServiceImpl");
        LoginLog loginLog = new LoginLog();
        loginLog.setId(IdGenerator.createNewId());
        loginLog.setUserAccount(user.getAccount());
        loginLog.setLoginIp(NetUtil.getIp(request));
        loginLog.setLogininTime(new Date());
        loginLog.setLoginState(Constants.USER_FLAG_LOGIN);
        service.save(loginLog);
    }
}
